package customer.zspt.cn.customer.activitys;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import customer.zspt.cn.customer.R;
import customer.zspt.cn.customer.constant.constant;
import customer.zspt.cn.customer.utils.GetNetWorkUtil;
import customer.zspt.cn.customer.utils.IntentUtils;
import customer.zspt.cn.customer.utils.SPUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
 * Created by Administrator on 2018/6/11 0011.
 */
public class login extends Activity implements View.OnClickListener {
    @ViewInject(R.id.tips)
    private View tips;
    @ViewInject(R.id.userName)
    private EditText userNameET;
    @ViewInject(R.id.password)
    private EditText passWordET;
    @ViewInject(R.id.login)
    private Button loginBT;
    @ViewInject(R.id.login_ll)
    private LinearLayout login_ll;
    @ViewInject(R.id.indexical_title)
    private TextView indexical_title;
    @ViewInject(R.id.prg_bar)
    private ProgressBar prg_bar;
    @ViewInject(R.id.tips_tv)
    private TextView tips_tv;
    /**显示与隐藏登录中提示框*/
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String token = (String) msg.obj;
            showTip(false);
            IntentUtils.startIntent(login.this,main.class);
            finish();
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        /**Xuti注解*/
        ViewUtils.inject(this);
        initLintener();
    }
    private void initLintener() {
        loginBT.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login:
                boolean netWorkState = GetNetWorkUtil.getNetWorkState(this);
                if (netWorkState){
                    login();
                }else{
                    tipToast("网络异常");
                }
                break;
        }
    }
     //登录操作
    private void login() {
        showTip(true);
        getLoginInfo();
    }
    /**获取登录信息*/
    private void getLoginInfo() {
        String username = userNameET.getText().toString().trim();
        String password = passWordET.getText().toString().trim();
        Gson gson = new Gson();
        Map<String,String> user = new HashMap<>();
        user.put("account",username);
        user.put("password",password);
        getCode(constant.LOGINFURL,gson.toJson(user));
    }
    /**是否显示登录中提示*/
    private void showTip(boolean IsShow) {
             if(IsShow) {
                 login_ll.setVisibility(View.INVISIBLE);
             } else{
                 login_ll.setVisibility(View.VISIBLE);
             }
             tips.setVisibility(IsShow?View.VISIBLE:View.GONE);
             indexical_title.setVisibility(!IsShow?View.VISIBLE:View.GONE);
             prg_bar.setVisibility(IsShow?View.VISIBLE:View.GONE);
             tips_tv.setVisibility(IsShow?View.VISIBLE:View.GONE);
    }
    private void getCode(final String url,final String jsonData) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                okHttpClient.newBuilder().connectTimeout(3000, TimeUnit.SECONDS).
                        readTimeout(3000,TimeUnit.SECONDS).writeTimeout(3000,TimeUnit.SECONDS).build();
                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                RequestBody body = RequestBody.create(JSON, jsonData);
                Request request = new Request.Builder().addHeader("Accept","application/json")
                        .addHeader("Connection","keep-alive")
                        .url(url)
                        .post(body)
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                          String tips = "";
                          if(e instanceof SocketException){
                              tips = "连接超时,请尝试重新登录或检查网络状态";
                          }else{
                              tips = "登录异常,请尝试重新登录或检查网络状态";
                          }
                          tipToast(tips);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String request = response.body().string();
                        try {
                            JSONObject codeObj = new JSONObject(request);
                             int code = codeObj.getInt("code");
                            if(code==0) {
                                String Logincode = codeObj.getJSONObject("data").getString("code");
                                getUser(constant.LOGINTURL,Logincode);
                            }else {
                                if(code == 20000){
                                    String tip = "检查您的用户名或密码是否存在错误";
                                    tipToast(tip);
                                }else{
                                    String tip = "登录异常,请尝试重新登录或检查网络状态";
                                    tipToast(tip);
                                }
                            }
                        } catch (JSONException e) {
                            String tip = "连接异常,请尝试重新登录或检查网络状态";
                            tipToast(tip);
                        }
                    }
                });
            }
        }).start();
    }
    private void getUser(final String url,final String code) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                okHttpClient.newBuilder().connectTimeout(3000, TimeUnit.SECONDS).readTimeout(3000, TimeUnit.SECONDS);
                RequestBody body = new FormBody.Builder()
                        .add("code", code).build();
                Request request = new Request.Builder().addHeader("Accept","application/json, text/plain, */*")
                        .addHeader("Connection","keep-alive")
                        .url(url)
                        .post(body)
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        String tip = "连接超时,请重新登录";
                        tipToast(tip);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        try {
                            JSONObject object = new JSONObject(result);
                            if(object.getInt("code")==0)
                            {
                                SPUtils.setString(getApplication(),constant.LOGINRESULT,result);
                                String token = object.getJSONObject("data").getString("token");
                                SPUtils.setString(getApplicationContext(),"token",token);
                                Message msg = new Message();
                                msg.obj = token;
                                mHandler.sendMessage(msg);
                            }
                        } catch (JSONException e) {
                                 e.printStackTrace();
                            String tip = "连接异常,请尝试重新登录或检查网络状态";
                            tipToast(tip);
                        }
                    }
                });
            }
        }).start();
    }
    public void tipToast(final String msg){
         runOnUiThread(new Runnable() {
             @Override
             public void run() {
                 Toast.makeText(getApplication(),msg,Toast.LENGTH_SHORT).show();
                 passWordET.setText("");
                 showTip(false);
             }
         });
    }
}
